using System;
using System.Collections.Generic;
using System.IO;
using System.Resources;
using PluginFrame;

namespace PcrDataStructure
{
    public class PcrDataService : IPlugin, IProvideService, IPcrDataService
    {
        private bool mIsSavingFile;

        private IApplication mApplication;

        private string mName = "";

        private string mDescription = "";

        private IConfigurationService mConfigurationService;

        private IMiscService mMiscService;

        private string mDefaultPcrDataFileName;

        private IPcrDataFile mDefaultPcrDataFile;

        private ResourceManager mResourceManager;

        private int mIndex;

        public int Index
        {
            get
            {
                return mIndex;
            }
            set
            {
                mIndex = value;
            }
        }

        public IApplication Application
        {
            get
            {
                return mApplication;
            }
            set
            {
                mApplication = value;
            }
        }

        public string Name
        {
            get
            {
                return mName;
            }
            set
            {
                mName = value;
            }
        }

        public string Description
        {
            get
            {
                return mDescription;
            }
            set
            {
                mDescription = value;
            }
        }

        public bool IsSavingFile
        {
            get
            {
                return mIsSavingFile;
            }
        }

        public event EventHandler<EventArgs> PluginEvent;

        public PcrDataService()
        {
            mApplication = null;
        }

        public void Execute(object[] context)
        {
        }

        public void UnLoad()
        {
        }

        public object ProvideService()
        {
            return null;
        }

        public void Load()
        {
            if (mApplication != null)
            {
                mApplication.AddService(mName, this);
                mConfigurationService = (IConfigurationService)mApplication.GetService("ConfigurationService");
                mMiscService = (IMiscService)mApplication.GetService("MiscService");
                mResourceManager = ResourceManager.CreateFileBasedResourceManager("PcrDataStructure", mApplication.GetResourceFolder() + GetType().Namespace + "\\", null);
                mDefaultPcrDataFileName = mApplication.GetAssemblyPath() + mConfigurationService.DefaultExperimentDataFile;
                mDefaultPcrDataFile = LoadDefaultPcrDataFile();
            }
        }

        public void SaveDefaultPcrDataFile(IPcrDataFile pcrDataFile)
        {
            string filePath = mApplication.GetAssemblyPath() + mConfigurationService.DefaultExperimentDataFile;
            IPcrDataFile pcrDataFile2 = LoadDefaultPcrDataFile();
            foreach (IPcrExperiment pcrExperiment2 in pcrDataFile2.CurrentPcrStructure.PcrExperiments)
            {
                List<IPcrExperiment> list = pcrDataFile.CurrentPcrStructure.FindExperimentWithSystemType(pcrExperiment2.SystemType);
                if (list != null && list.Count > 0)
                {
                    IPcrExperiment pcrExperiment = list[list.Count - 1];
                    pcrExperiment2.IsUseHotLid = pcrExperiment.IsUseHotLid;
                    pcrExperiment2.TemperatureControlType = pcrExperiment.TemperatureControlType;
                    pcrExperiment2.TubeVolume = pcrExperiment.TubeVolume;
                    pcrExperiment2.Assessor = pcrExperiment.Assessor;
                    pcrExperiment2.Operator = pcrExperiment.Operator;
                    pcrExperiment2.ColumnConfiguration = pcrExperiment.ColumnConfiguration;
                    pcrExperiment2.ColumnList = pcrExperiment.ColumnList;
                }
            }
            SavePcrDataFile(filePath, pcrDataFile2);
        }

        public IPcrDataFile LoadDefaultPcrDataFile()
        {
            IPcrDataFile pcrDataFile = null;
            try
            {
                pcrDataFile = LoadPcrDataFile(mDefaultPcrDataFileName, false);
                if (pcrDataFile.CurrentPcrStructure.PcrExperiments.Count <= 0)
                {
                    pcrDataFile = null;
                }
            }
            catch
            {
                pcrDataFile = CreateDefaultPcrFile();
            }
            finally
            {
                if (pcrDataFile == null)
                {
                    pcrDataFile = CreateDefaultPcrFile();
                }
            }
            return pcrDataFile;
        }

        public IPcrDataFile CreateDefaultPcrFile()
        {
            IPcrDataFile pcrDataFile = new PcrDataFile(mApplication);
            GenerateDefaultPcrStructure(pcrDataFile);
            pcrDataFile.DataFileFolder = mApplication.GetAssemblyPath() + mConfigurationService.DataFileDefaultFolder + "\\";
            pcrDataFile.ReportFileFolder = mApplication.GetAssemblyPath() + mConfigurationService.ReportFileDefaultFolder + "\\";
            pcrDataFile.ProjectFileFolder = mApplication.GetAssemblyPath() + mConfigurationService.ProjectFileDefaultFolder + "\\";
            pcrDataFile.PcrCfgFileFolder = mApplication.GetAssemblyPath() + mConfigurationService.PcrCfgFileDefaultFolder + "\\";
            pcrDataFile.CreateTime = DateTime.Now;
            pcrDataFile.ModificationTime = DateTime.Now;
            pcrDataFile.IsNewPcrFile = true;
            pcrDataFile.Language = mConfigurationService.UICultureString;
            SavePcrDataFile(mDefaultPcrDataFileName, pcrDataFile);
            IPcrDataFile pcrDataFile2 = LoadPcrDataFile(mDefaultPcrDataFileName, false);
            if (pcrDataFile2 == null)
            {
                return null;
            }
            CopyToResource();
            pcrDataFile2.Application = mApplication;
            return pcrDataFile2;
        }

        private void CopyToResource()
        {
            try
            {
                string sourceFileName = mApplication.GetAssemblyPath() + "default.dat";
                string text = mConfigurationService.UICultureString.ToString();
                string text2 = mApplication.GetAssemblyPath() + "Resource\\" + text + "\\";
                if (!Directory.Exists(text2))
                {
                    Directory.CreateDirectory(text2);
                }
                string destFileName = text2 + "default_" + text + ".dat";
                File.Copy(sourceFileName, destFileName, true);
            }
            catch (Exception)
            {
            }
        }

        public IPcrDataFile CreateNewPcrDataFile()
        {
            return new PcrDataFile(mApplication);
        }

        public IPcrStructure GenerateDefaultPcrStructure(IPcrDataFile defaultPcrDataFile)
        {
            IPcrStructure pcrStructure = new PcrStructure(defaultPcrDataFile, mConfigurationService.GetCellIDPositionMapDictionary(), mConfigurationService.ChannelConfigurations());
            byte[] array = new byte[pcrStructure.ChannelConfigurations.Length];
            IChannelConfiguration[] channelConfigurations = pcrStructure.ChannelConfigurations;
            foreach (IChannelConfiguration channelConfiguration in channelConfigurations)
            {
                array[channelConfiguration.Position] = (byte)(channelConfiguration.IsAvailable ? 1u : 0u);
            }
            pcrStructure.PcrInstrument.InitializeInstrumentData("default", array, true);
            pcrStructure.State = PcrModuleState.Single;
            pcrStructure.CreateTime = DateTime.Now;
            int num = 1;
            for (int j = 0; j < mConfigurationService.ModuleCount; j++)
            {
                IPcrModule pcrModule = new PcrModule(pcrStructure);
                pcrModule.ModuleID = mConfigurationService.GetModuleNameFromID(j + 1);
                int moduleIndex = pcrModule.GetModuleIndex();
                if (moduleIndex < mConfigurationService.ModuleUseHotLid.Length)
                {
                    pcrModule.UseHotlid = mConfigurationService.ModuleUseHotLid[moduleIndex];
                }
                else
                {
                    pcrModule.UseHotlid = mConfigurationService.DefaultUseHotLid;
                }
                pcrModule.HotLidTemperaure = mConfigurationService.HotLidTemperature;
                pcrModule.CanbeUsed = true;
                pcrStructure.AddPcrModule(pcrModule);
                List<string> columnList = mConfigurationService.GetColumnList();
                for (int k = 0; k < mConfigurationService.SubModuleCount; k++)
                {
                    IExperimentSubModule experimentSubModule = new ExperimentSubModule();
                    experimentSubModule.ID = num - 1;
                    experimentSubModule.PcrModule = pcrModule;
                    List<int> cellIDsFromSubModule = pcrStructure.GetCellIDsFromSubModule(num);
                    num++;
                    foreach (int item2 in cellIDsFromSubModule)
                    {
                        string cellPosition = pcrStructure.GetCellIDPositionMap(item2).CellPosition();
                        IPcrCell item = new PcrCell(item2, cellPosition, experimentSubModule, mConfigurationService.ChannelCount, columnList);
                        experimentSubModule.PcrCells.Add(item);
                    }
                    pcrModule.SubModules.Add(experimentSubModule);
                }
            }
            string text = mMiscService.TimeToFileFormatString(DateTime.Now, "_");
            pcrStructure.CreateNewExperiment("Experiment_" + text, PcrSystemType.AbsoluteAnalysis);
            pcrStructure.CreateNewExperiment("Experiment_" + text, PcrSystemType.Allele);
            pcrStructure.CreateNewExperiment("Experiment_" + text, PcrSystemType.GeneScan);
            return pcrStructure;
        }

        public IPcrDataFile LoadPcrDataFile(string file, bool isShowHint)
        {
            IPcrDataFile pcrDataFile = null;
            if (!string.IsNullOrEmpty(file) && File.Exists(file))
            {
                bool flag = Path.GetExtension(file).Equals(".cfg");
                pcrDataFile = (IPcrDataFile)mMiscService.DeSerializeBinaryFile(file);
                LanguageStrings language = pcrDataFile.Language;
                pcrDataFile.Application = mApplication;
                pcrDataFile.FilePath = file;
                if (pcrDataFile.CurrentPcrStructure != null)
                {
                    List<IPcrExperiment> pcrExperiments = pcrDataFile.CurrentPcrStructure.PcrExperiments;
                    if (pcrExperiments != null && pcrExperiments.Count > 0 && !flag)
                    {
                        if (!pcrDataFile.IsNewPcrFile)
                        {
                            pcrExperiments[0].ResultFile = file;
                        }
                        pcrExperiments[0].Name = Path.GetFileNameWithoutExtension(pcrExperiments[0].ResultFile);
                        foreach (IPcrStructure pcrStructure in pcrDataFile.PcrStructureList)
                        {
                            foreach (IPcrExperiment pcrExperiment in pcrStructure.PcrExperiments)
                            {
                                bool isNewPcrFile = pcrDataFile.IsNewPcrFile;
                                pcrExperiment.Initialize(mApplication);
                                pcrExperiment.TabDisplayName = pcrExperiment.Name;
                                foreach (IPcrExperimentProject project in pcrExperiment.Projects)
                                {
                                    bool isNewPcrFile2 = pcrDataFile.IsNewPcrFile;
                                    IProjectItem[] projectItems = project.ProjectItems;
                                    foreach (IProjectItem projectItem in projectItems)
                                    {
                                        if (projectItem != null)
                                        {
                                            projectItem.ChannelConfiguration.IsAvailable = projectItem.ChannelConfiguration.IsSelected;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return pcrDataFile;
        }

        public void SavePcrDataFile(string filePath, IPcrDataFile pcrDataFile)
        {
            if (mIsSavingFile)
            {
                return;
            }
            bool flag = Path.GetExtension(filePath).Equals(".cfg");
            mIsSavingFile = true;
            pcrDataFile.IsChanged = false;
            pcrDataFile.FilePath = filePath;
            pcrDataFile.Language = mConfigurationService.UICultureString;
            if (pcrDataFile.CurrentPcrStructure != null)
            {
                List<IPcrExperiment> pcrExperiments = pcrDataFile.CurrentPcrStructure.PcrExperiments;
                if (pcrExperiments != null && pcrExperiments.Count > 0 && !flag)
                {
                    if (!pcrDataFile.IsNewPcrFile)
                    {
                        pcrExperiments[0].ResultFile = filePath;
                    }
                    pcrExperiments[0].Name = Path.GetFileNameWithoutExtension(pcrExperiments[0].ResultFile);
                    pcrExperiments[0].TabDisplayName = pcrExperiments[0].Name;
                }
            }
            mMiscService.SerializeBinaryFile(filePath, FileMode.Create, pcrDataFile);
            mIsSavingFile = false;
        }

        public void DeletePcrDataFile(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        public void UpdateDefaultPcrChannelUsed(List<bool> isChannelUsed)
        {
            IPcrStructure currentPcrStructure = mDefaultPcrDataFile.CurrentPcrStructure;
            if (currentPcrStructure != null)
            {
                SavePcrDataFile(mDefaultPcrDataFileName, mDefaultPcrDataFile);
            }
        }

        public void UpdateDefaultPcrControlTypeUsed(TemperatureControlType controlType, double volume)
        {
            IPcrStructure currentPcrStructure = mDefaultPcrDataFile.CurrentPcrStructure;
            if (currentPcrStructure == null)
            {
                return;
            }
            foreach (IPcrExperiment pcrExperiment in currentPcrStructure.PcrExperiments)
            {
                IPcrExperiment pcrExperiment2 = pcrExperiment;
            }
            SavePcrDataFile(mDefaultPcrDataFileName, mDefaultPcrDataFile);
        }

        public bool SaveStandardCurve(string filePath, IPcrExperimentProject pcrProject, IPcrExperiment pcrExperiment)
        {
            try
            {
                if (pcrExperiment != null && pcrProject != null)
                {
                    if (pcrExperiment.PcrStructure.PcrDataFile.IsNewPcrFile)
                    {
                        return false;
                    }
                    foreach (IPcrExperimentProject project in pcrExperiment.Projects)
                    {
                        if (project.Equals(pcrProject))
                        {
                            IAnalysisResult[,] analysisResults = pcrExperiment.GetAnalysisResults(project);
                            mMiscService.SerializeBinaryFile(filePath, FileMode.Create, analysisResults);
                            analysisResults = mMiscService.DeSerializeBinaryFile(filePath) as IAnalysisResult[,];
                            IPcrStandardCurve pcrStandardCurve = new PcrStandardCurve(analysisResults, pcrExperiment, project);
                            pcrStandardCurve.FileName = Path.GetFileName(filePath);
                            mMiscService.SerializeBinaryFile(filePath, FileMode.Create, pcrStandardCurve);
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public IPcrStandardCurve LoadStandardCurve(string filePath)
        {
            IPcrStandardCurve pcrStandardCurve = mMiscService.DeSerializeBinaryFile(filePath) as IPcrStandardCurve;
            if (pcrStandardCurve != null)
            {
                Path.GetFileNameWithoutExtension(filePath);
            }
            return pcrStandardCurve;
        }
    }
}
